package org.rainwalk.bill.task;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.rainwalk.bill.entity.Token;
import org.rainwalk.bill.model.enums.TokenStateEnum;
import org.rainwalk.bill.service.ITokenService;
import org.rainwalk.bill.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * token相关任务调度
 *
 * @author chenyuheng create class on 2021-03-17
 */
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class TokenTask {

    @Value("${const.token.ttl}")
    private int tokenTtl;

    private final ITokenService tokenService;

    /**
     * 每天清除过期的token
     * cron：0 0 2 * * ? = 每天2点
     */
//    @Scheduled(cron = "0 0 2 * * ? ")
    public void clearExpiredToken() {
        LambdaUpdateWrapper<Token> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.lt(Token::getRefreshTime, TimeUtil.getNow() - tokenTtl);
        log.info("准备清除过期token");
        tokenService.remove(updateWrapper);
        log.info("清除过期token完毕");
    }

    /**
     * 每10分钟检查一遍token失效情况
     */
    @Scheduled(cron = "0 0/10 * * * ? ")
    public void checkExpiredToken() {
        LambdaUpdateWrapper<Token> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.lt(Token::getRefreshTime, TimeUtil.getNow() - tokenTtl)
                .eq(Token::getState, TokenStateEnum.EFFECTIVE.getValue())
                .set(Token::getState, TokenStateEnum.INVALID.getValue());
        tokenService.update(updateWrapper);
    }


}
